﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.Revit;

namespace YArchitech.Plumbing
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class ThwartwisePipeConnectRiserPipe : HYExternalCommand
	{
		public override Result HYExecute(ref string TranName)
		{
			TranName = "横管连接立管";
			IList<Element> list = new List<Element>();
			ISelectionFilter selectionFilter = new PipeFilter();
			FormTPipeconnectRPipe formTPipeconnectRPipe = new FormTPipeconnectRPipe();
			string text = "";
			FamilySymbol familySymbolByName = YJKRevitTools.GetFamilySymbolByName("Fitting", "顺水三通", base.Doc, ref text);
			bool isSSTee = false;
			if (familySymbolByName.Family.Name.Contains("顺水"))
			{
				isSSTee = true;
			}
			YJKWindowHandle owner = new YJKWindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			formTPipeconnectRPipe.Show(owner);
			for (;;)
			{
				try
				{
					if (formTPipeconnectRPipe.Visible)
					{
						list = base.Sel.PickElementsByRectangle(selectionFilter, "请框选要连接的立管与横管");
						if (list.Count != 2)
						{
							YJKMessageBox.Show("必须选择一根立管与一根横管！");
						}
						else if (list.Count == 2)
						{
							YJKPipeConnectorHelper hypipeConnectorHelper = new YJKPipeConnectorHelper();
							List<Pipe> list2 = new List<Pipe>();
							list2 = new YJKRevitTools().TwoPipesOneisRightAndOneIsNot(list.ElementAt(0) as Pipe, list.ElementAt(1) as Pipe);
							if (list2 != null && list2.Count >= 2)
							{
								string text2 = "";
								hypipeConnectorHelper.TPipeConnectRPipe(list2.ElementAt(0), list2.ElementAt(1), base.Doc, familySymbolByName, isSSTee, this.whatFuction(formTPipeconnectRPipe.message), ref text2, false);
								if (text2 != "")
								{
									YJKMessageBox.Show(text2);
								}
							}
						}
						continue;
					}
				}
				catch (Autodesk.Revit.Exceptions.OperationCanceledException)
				{
				}
				break;
			}
			if (formTPipeconnectRPipe.message != "")
			{
				string message = formTPipeconnectRPipe.message;
				formTPipeconnectRPipe.userSetting.WriteTRPipeConnectText(message);
			}
			formTPipeconnectRPipe.Close();
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private int whatFuction(string message)
		{
			int result;
			if (!(message == "立管为基准管，横管与立管对齐。"))
			{
				if (!(message == "横管为基准管，立管与横管对齐。"))
				{
					if (!(message == "直径大的为基准管，相等时横管为基准管。"))
					{
						if (!(message == "不做对齐操作直接连接。"))
						{
							result = 0;
						}
						else
						{
							result = 0;
						}
					}
					else
					{
						result = 3;
					}
				}
				else
				{
					result = 2;
				}
			}
			else
			{
				result = 1;
			}
			return result;
		}
	}
}
